#!/usr/bin/python2

import glob
import Queue
from os.path import basename
import subprocess
import sys

PER_HOUR = '10000'
CITIES = ['austin', 'baton_rouge', 'seattle', 'sf']
MODES = ['fifo', 'auction-sys', 'auction-no-sys', 'equal-sys', 'equal-no-sys',
         'fixed-sys', 'fixed-no-sys']
TRIALS = 3
THREADS = 4

def launch(argv):
  print 'Running:', ' '.join(argv)
  return subprocess.Popen(argv)

if __name__ == '__main__':
  queue = Queue.Queue()
  command = sys.argv[1]

  if command == 'generate':
    for city in CITIES:
      for trial in xrange(1, TRIALS + 1):
        queue.put(
          ['./tools/auction_experiment', 'all', city, PER_HOUR, str(trial)]
        )
  elif command == 'run':
    for scenario in glob.glob("scenarios/*"):
      queue.put(['./tools/run', basename(scenario)])
  elif command == 'finalize':
    for scenario in glob.glob("logs/*"):
      queue.put(['./tools/finalize', basename(scenario)])

  processes = set()
  for i in xrange(THREADS):
    if not queue.empty():
      processes.add(launch(queue.get()))

  try:
    while len(processes) > 0:
      reap = set([p for p in processes if p.poll() is not None])
      processes -= reap
      # Replace with new processes
      for i in xrange(len(reap)):
        if not queue.empty():
          processes.add(launch(queue.get()))
  except KeyboardInterrupt:
    sys.exit
